import {
	onMounted,
	onBeforeUnmount,
	onActivated,
	onDeactivated,
	ref,
	unref,
	Ref,
	nextTick,
} from "vue";
import { MayBeRef } from "@/model/util";

export interface ParentEventOptions {
	event?: string;
	level?: number;
	stop?: boolean;
}

export default function <T = any, R = any>(
	curretNode: MayBeRef<R>,
	fn: (back?: Ref<T>) => void,
	option?: ParentEventOptions,
) {
	const parentNode = ref<any>();

	function publicEvent(e: Event) {
		const stop = option?.stop || true;
		stop && e.stopPropagation();
		fn(parentNode.value);
	}

	async function onEvent() {
		const event = option?.event || "click";
		const level = option?.level || 1;
		await nextTick();
		parentNode.value = (unref(curretNode) as any).$el;
		for (let i = 0; i < level; i++) {
			parentNode.value = parentNode.value.parentNode;
		}
		parentNode.value.addEventListener(event, publicEvent);
	}
	async function offEvent() {
		await nextTick();
		const event = option?.event || "click";
		parentNode.value.removeEventListener(event, publicEvent);
	}

	onMounted(() => {
		onEvent();
	});
	onActivated(() => {
		onEvent();
	});

	onBeforeUnmount(() => {
		offEvent();
	});
	onDeactivated(() => {
		offEvent();
	});

	return parentNode;
}
